# -*- coding: utf-8 -*-
"""
Created on Mon Mar 29 12:35:37 2021

@author: Apple
"""


import os
import pandas as pd
import numpy as np
import sys
from PyQt5 import QtCore,QtWidgets,QtGui
from PyQt5.QtWidgets import (QMainWindow,QWidget,QTableWidget,QHBoxLayout,QTableWidgetItem,QMessageBox,QApplication,QTableWidgetItem,QHeaderView,QAbstractItemView)
from PyQt5.QtCore import Qt, QEventLoop, QTimer
from PyQt5.QtGui import QPixmap
from main_window import Ui_MainWindow
from 算法 import *
import matplotlib.pyplot as plt


class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.label_pic.setFrameShape(QtWidgets.QFrame.Box)
        self.ui.actionopen.triggered.connect(self.openfile)
        self.ui.actionversion.triggered.connect(self.showversion)
        global numL
        global numC
        numL = 0
        numC = 0
        tableWidget1 = self.ui.tableWidget1
        tableWidget1.setRowCount(1)
        tableWidget1.setColumnCount(4)
        tableWidget1.setHorizontalHeaderLabels(['编号','库存容量（吨）','单位周转费用（元/kg）','年固定费用（元）'])
        tableWidget1.setColumnWidth(2,200)
        tableWidget1.setColumnWidth(3,200)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,0,newItem)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,1,newItem)      

        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,2,newItem)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,3,newItem)

        tableWidget2 = self.ui.tableWidget2
        tableWidget2.setRowCount(1)
        tableWidget2.setColumnCount(2)
        tableWidget2.setHorizontalHeaderLabels(['编号','年需求量（吨）'])
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget2.setItem(0,0,newItem)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget2.setItem(0,1,newItem)   
        
    def openfile(self):
        path = os.getcwd() 
        os.startfile(path)
    
    def showversion(self):
        QMessageBox.about(self, '关于', '当前版号为 V1.0 ')        
        
    def listoftabL(self):
        global numL
        data = self.ui.lineEditnumL.text()
        numL = data
        if data.isdigit():
            print('it is an integer')
        else:
            print('Please input an *integer*')
            QMessageBox.about(self, '警告', '请输入一个正整数')
            return            
        # print(data)
        data = int(data)
        tableWidget1 = self.ui.tableWidget1
        num = tableWidget1.rowCount()
        if num < data:
            
            for i in range(num,data):
                tableWidget1.insertRow(i)
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget1.setItem(i,0,newItem)
                
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget1.setItem(i,1,newItem)      
        
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget1.setItem(i,2,newItem)
                
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget1.setItem(i,3,newItem)
        else:
            for i in range(num,data-1,-1):
                tableWidget1.removeRow(i)
           
            
        
    def newlineL(self):
        tableWidget1 = self.ui.tableWidget1
        num = tableWidget1.rowCount()
        tableWidget1.insertRow(num)
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(num,0,newItem)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(num,1,newItem)      

        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(num,2,newItem)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(num,3,newItem)
        self.ui.lineEditnumL.setText(str(num+1))
        global numL
        numL = num+1


    def dellineL(self):
        tableWidget1 = self.ui.tableWidget1
        num = tableWidget1.rowCount()
        if num == 1:
            tableWidget1.removeRow(0)
            tableWidget1.insertRow(0)
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget1.setItem(0,0,newItem)
            
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget1.setItem(0,1,newItem)      
    
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget1.setItem(0,2,newItem)

            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget1.setItem(0,3,newItem)
        else:
            tableWidget1.removeRow(num-1) 
        self.ui.lineEditnumL.setText(str(num-1))
        global numL
        numL = num-1
        
    def clearResultL(self):
        tableWidget1 = self.ui.tableWidget1
        tableWidget1.setRowCount(0) # 设置行数
        tableWidget1.setRowCount(1)
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,0,newItem)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,1,newItem)      

        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,2,newItem)

        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget1.setItem(0,3,newItem)
        self.ui.lineEditnumL.clear()
        global numL
        global numC
        numL = 0
        numC = 0
    
    def savedataL(self):
        tableWidget1 = self.ui.tableWidget1
        numrow = tableWidget1.rowCount()
        numcol = tableWidget1.columnCount()
        listall = []
        for i in range(numrow):
            listcol = []
            for j in range(numcol):
                data = tableWidget1.item(i,j).text()
                if data =='':
                    QMessageBox.about(self, '警告', '请输入完整数据')
                    return
                else:
                    listcol.append(data)
            listall.append(listcol)
        print(listall)
        path = os.getcwd() + '\\1.csv'
        print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = listall)
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功')

    def listoftabC(self):
        global numC
        data = self.ui.lineEditnumC.text()
        numC = data
        if data.isdigit():
            print('it is an integer')
        else:
            print('Please input an *integer*')
            QMessageBox.about(self, '警告', '请输入一个正整数')
            return            
        # print(data)
        data = int(data)
        tableWidget2 = self.ui.tableWidget2
        num = tableWidget2.rowCount()
        if num < data:
            
            for i in range(num,data):
                tableWidget2.insertRow(i)
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget2.setItem(i,0,newItem)
                
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget2.setItem(i,1,newItem)      
        
        else:
            for i in range(num,data-1,-1):
                tableWidget2.removeRow(i)
           
            
        
    def newlineC(self):
        tableWidget2 = self.ui.tableWidget2
        num = tableWidget2.rowCount()
        tableWidget2.insertRow(num)
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget2.setItem(num,0,newItem)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget2.setItem(num,1,newItem)
        self.ui.lineEditnumC.setText(str(num+1))
        global numC
        numC = num+1


    def dellineC(self):
        tableWidget2 = self.ui.tableWidget2
        num = tableWidget2.rowCount()
        if num == 1:
            tableWidget2.removeRow(0)
            tableWidget2.insertRow(0)
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget2.setItem(0,0,newItem)
            
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget2.setItem(0,1,newItem)      
    
        else:
            tableWidget2.removeRow(num-1)
        self.ui.lineEditnumC.setText(str(num-1))
        global numC
        numC = num-1
        
    def clearResultC(self):
        tableWidget2 = self.ui.tableWidget2
        tableWidget2.setRowCount(0) # 设置行数
        tableWidget2.setRowCount(1)
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget2.setItem(0,0,newItem)
        
        newItem = QTableWidgetItem('')
        newItem.setTextAlignment(Qt.AlignCenter)
        tableWidget2.setItem(0,1,newItem)  
        self.ui.lineEditnumC.clear()
        global numC
        global numL
        numL = 0
        numC = 0
    
    def savedataC(self):
        tableWidget2 = self.ui.tableWidget2
        numrow = tableWidget2.rowCount()
        numcol = tableWidget2.columnCount()
        listall = []
        for i in range(numrow):
            listcol = []
            for j in range(numcol):
                data = tableWidget2.item(i,j).text()
                if data =='':
                    QMessageBox.about(self, '警告', '请输入完整数据')
                    return
                else:
                    listcol.append(data)
            listall.append(listcol)
        print(listall)
        path = os.getcwd() + '\\2.csv'
        print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = listall)
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功') 
    
    def listoftabR(self):
        global numL
        global numC
        numL = int(numL)
        numC = int(numC)
        tableWidget3 = self.ui.tableWidget3
        tableWidget3.setRowCount(numC)
        tableWidget3.setColumnCount(numL)
        a = []
        b = []
        for i in range(1,numL+1):
            a.append(f'物流中心{i}')
        for i in range(1,numC+1):
            b.append(f'客户{i}')        
        tableWidget3.setHorizontalHeaderLabels(a)
        tableWidget3.setVerticalHeaderLabels(b)
        for i in range(numC):
            for j in range(numL):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget3.setItem(i,j,newItem)
                
    def newlineR(self):
        tableWidget3 = self.ui.tableWidget3
        numR = tableWidget3.rowCount()
        numC = tableWidget3.colorCount()
        tableWidget3.insertRow(numR)
        for i in range(numC):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget3.setItem(numR,i,newItem)




    def dellineR(self):
        tableWidget3 = self.ui.tableWidget3
        numR = tableWidget3.rowCount()
        numC = tableWidget3.colorCount()
        if numR == 1:
            tableWidget3.removeRow(0)
            tableWidget3.insertRow(0)
        for i in range(numC):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget3.setItem(0,i,newItem)
        else:
            tableWidget3.removeRow(numR-1)

        
    def clearResultR(self):
        self.ui.tableWidget3.clear()
        self.ui.tableWidget3.setColumnCount(0)
        self.ui.tableWidget3.setRowCount(0)


    
    def savedataR(self):
        global numL
        global numC
        numL = int(numL)
        numC = int(numC)
        tableWidget3 = self.ui.tableWidget3
        numrow = tableWidget3.rowCount()
        numcol = tableWidget3.columnCount()
        listall = []
        for i in range(numrow):
            listcol = []
            for j in range(numcol):
                data = tableWidget3.item(i,j).text()
                if data =='':
                    QMessageBox.about(self, '警告', '请输入完整数据')
                    return
                else:
                    listcol.append(data)
            listall.append(listcol)
        print(listall)
        if numC != numrow or numL != numcol:
            QMessageBox.about(self, '警告', '输入行列与设置行列不一致')
            return
        path = os.getcwd() + '\\3.csv'
        print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = listall)
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功') 
        
        
    
    def showinformationL(self):
        self.ui.tableWidget4.clear()
        self.ui.tableWidget4.setColumnCount(0)
        self.ui.tableWidget4.setRowCount(0) 
        data = pd.read_csv('1.csv')
        Data = data.iloc[:,:].values.tolist() # 转换为list
        a = np.shape(data)[0] # 行数
        b = np.shape(data)[1] # 列数 
        tableWidget4 = self.ui.tableWidget4
        tableWidget4.setRowCount(a)
        tableWidget4.setColumnCount(b)
        tableWidget4.setHorizontalHeaderLabels(['编号','库存容量（吨）','单位周转费用（元/吨）','年固定费用（元）'])
        tableWidget4.setColumnWidth(2,200)
        tableWidget4.setColumnWidth(3,200)
        for i in range(a):
            for j in range(b):
                newItem = QTableWidgetItem(str(Data[i][j]))
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget4.setItem(i,j,newItem)
        tableWidget4.setEditTriggers(QAbstractItemView.NoEditTriggers)

    def showinformationC(self):
        self.ui.tableWidget4.clear()
        self.ui.tableWidget4.setColumnCount(0)
        self.ui.tableWidget4.setRowCount(0) 
        data = pd.read_csv('2.csv')
        Data = data.iloc[:,:].values.tolist() # 转换为list
        a = np.shape(data)[0] # 行数
        b = np.shape(data)[1] # 列数 
        tableWidget4 = self.ui.tableWidget4
        tableWidget4.setRowCount(a)
        tableWidget4.setColumnCount(b)
        tableWidget4.setHorizontalHeaderLabels(['编号','年需求量（吨）'])
        for i in range(a):
            for j in range(b):
                newItem = QTableWidgetItem(str(Data[i][j]))
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget4.setItem(i,j,newItem)
        tableWidget4.setEditTriggers(QAbstractItemView.NoEditTriggers)

    def showinformationR(self):
        data1 = pd.read_csv('3.csv')
        data2 = pd.read_csv('1.csv')
        Data1 = data1.iloc[:,:].values.tolist()
        Data2 = data2.iloc[:,:].values.tolist()
        a = np.shape(data1)[0] # 行数
        b = np.shape(data1)[1] # 列数
        for i in range(a):
            for j in range(b):
                Data1[i][j] = Data1[i][j] + Data2[j][2]
        tableWidget4 = self.ui.tableWidget4
        tableWidget4.setRowCount(a)
        tableWidget4.setColumnCount(b)
        A = []
        B = []
        for i in range(1,b+1):
            A.append(f'物流中心{i}')
        for i in range(1,a+1):
            B.append(f'客户{i}')        
        tableWidget4.setHorizontalHeaderLabels(A)
        tableWidget4.setVerticalHeaderLabels(B)
        for i in range(a):
            for j in range(b):
                newItem = QTableWidgetItem(str(Data1[i][j]))
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget4.setItem(i,j,newItem)
        tableWidget4.setEditTriggers(QAbstractItemView.NoEditTriggers)
    
    def clearResultS(self):
        self.ui.tableWidget4.clear()
        self.ui.tableWidget4.setColumnCount(0)
        self.ui.tableWidget4.setRowCount(0) 
    
    def savesettings(self):
        
        settings = []
        settings.append(self.ui.LEpopsize.text())
        settings.append(self.ui.LEiterations.text())
        settings.append(self.ui.LEpc.text())
        settings.append(self.ui.LEpm.text())
        for i in range(4):
            data = settings[i]
            if data =='':
                QMessageBox.about(self, '警告', '请输入完整数据')
                return
        print(settings)
        path = os.getcwd() + '\\4.csv'
        print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = settings)
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功')


    def runexe(self):
        
        A = [] # 物流中心容量
        B = [] # 需求点的需求量
        D = [] # 各地设置物流中心的固定费用
        data1 = pd.read_csv('1.csv')
        data2 = pd.read_csv('2.csv')
        data3 = pd.read_csv('4.csv')
        Data1 = data1.iloc[:,:].values.tolist() 
        Data2 = data2.iloc[:,:].values.tolist()
        numrow1 = np.shape(data1)[0] 
        numrow2 = np.shape(data2)[0] 
        for i in range(numrow1):
            A.append(Data1[i][1])
            D.append(Data1[i][3])
            
        for i in range(numrow2):
            B.append(Data2[i][1])
        
        numa = np.shape(data1)[0]
        numb = np.shape(data2)[0] 
        Y = []  # 定义变量码
        Y_decode = []  # 定义解码生成的变量码
        m = numrow1 # 染色体长度（物流中心个数）
        T = int(data3.loc[1]) # 迭代次数
        Popsize = int(data3.loc[0])# 种群规模
        decode_after_chrom2 = np.zeros((Popsize, m))    
        datas = dict()  # 定义一个空字典 (产地,销地):运价
        datac = dict()  # 定义一个空字典   产地:产量
        datax = dict()  # 定义一个空字典   销地:销量
        fixed_cost = 0.0  # 初始固定成本
        X = np.zeros((m, len(B)))  # 运量矩阵
        transport_cost = 0.0  # 初始运输费用
        cost = 0.0  # 初始总费用
        
        best_y = np.zeros((1, m))  # 所有代中的最优选址方案
        min_t = 100  # 最优的方案出现的代数
        all_min_cost = 999999999999  # 所有代中最小总费用
        all_min_X = np.zeros((m, len(B)))  # 所有代中最小总费用的运量矩阵
        FitnV = np.zeros((1, Popsize))  # 适应度列表
        New_chrom1 = np.zeros((Popsize, m))
        New_chrom2 = np.zeros((Popsize, m))
        Result = np.zeros((T,1))
        ResultText = ''
        
        # ---------------------遗传编码---------------------------
        
        # 生成附加码
        FA = []
        FB = []
        FDR = []
        for i in range(m):
            FA.append(1)
            FB.append(m)
        FDR.append(FA)
        FDR.append(FB)
        FDR.append(FA)   
        FieldDR = np.array(FDR)
        chrom1 = ga.crtpp(Popsize, FieldDR)  # 种群大小，上界下界区域描述器
        
        # 生成变量码
        chrom2 = ga.crtbp(Popsize, m)
        
        add_code = np.zeros((1, m))  # 定义父代单行附加码
        new_add_code = np.zeros((1, m))  # 定义子代单行附加码
        variable_code = np.zeros((1, m))  # 定义父代单行变量码
        new_variable_code = np.zeros((1, m))  # 定义子代单行变量码
        index_v = 0  # 定义初始索引值
        begin_New_chrom2 = np.zeros((Popsize, m))  # 定义经过交叉后的新的变量码种群
        again_New_chrom1 = np.zeros((Popsize, m))  # 经过变异后的附加码种群
        a = 0
        for t in np.arange(0, T):
            min_cost =  9999999999  # 初始最小总费用
            min_X = np.zeros((m, len(B)))  # 初始最小总费用的运量矩阵
            min_i = 0  # 每一代中最小的运价在种群对应的位置
            better_y = np.zeros((1, m))  # 每一代中的最优选址方案
          # print("==========================第%d代种群======================" % t)
        
            for i in np.arange(0, Popsize):
                Y = chrom2[i]
                Y_decode = np.array(decode(Y, A, B, m))
                decode_after_chrom2[i] = Y_decode
                List2 = np.multiply(np.array(D), Y_decode)  # 计算 d*y
                fixed_cost = Fixed_cost(List2)
                (datas, datac, datax) = report(Y_decode, A, B,numa,numb)
                (X, transport_cost) = Transport_cost(datas, datac, datax,numa,numb)
                cost = fixed_cost + transport_cost

                FitnV[0][i] = 1 / cost
                if cost < min_cost:
                    min_cost = cost
                    min_X = X
                    min_i = i
                    better_y = Y_decode
                    
            for i in range(Popsize): # 锦标赛选择方法
                list4 = []
                list3 =  random.sample([i for i in range(Popsize)],10)
                for j in list3:
                    list4.append(FitnV[0][j])
                max_index = list4.index(max(list4))
                New_chrom1[i] = chrom1[list3[max_index]]
                New_chrom2[i] = decode_after_chrom2[list3[max_index]]
                
            # 遗传操作
            Pc = float(data3.loc[2]) # 交叉概率
            Pm = float(data3.loc[3]) # 变异概率
                        
            New_chrom1 = ga.xovpmx(New_chrom1, Pc)
            
            for change_1 in np.arange(0, Popsize):
                new_add_code = New_chrom1[change_1]
                add_code = chrom1[change_1]
                variable_code = New_chrom2[change_1]
                for change_2 in np.arange(0, m):
                    index_v = add_code.tolist().index(new_add_code[change_2])
                    new_variable_code[0, change_2] = variable_code[index_v]
                begin_New_chrom2[change_1] = new_variable_code
                new_variable_code = np.zeros((1, m))
        
            # 变异操作
            ret = np.random.random()
            if ret > Pm:
                for mutation_v in np.arange(0, Popsize):
                    new_add_code = New_chrom1[mutation_v]
                    random_1 = np.random.randint(0, m)
                    random_2 = np.random.randint(0, m)
                    a = np.abs(random_1 - random_2)
                    tem_list = np.zeros(a + 1)
                    if a != 0:
                        if random_2 > random_1:
                            for i, k in zip(np.arange(0, np.abs(random_2 - random_1) + 1), np.arange(random_1, random_2 + 1)):
                                tem_list[i] = new_add_code[k]
                            tem_list = tem_list.tolist()
                            tem_list.reverse()
        
                            for i, k in zip(np.arange(0, np.abs(random_2 - random_1) + 1).tolist(),
                                            np.arange(random_1, random_2 + 1).tolist()):
                                new_add_code[k] = tem_list[i]
        
                            again_New_chrom1[mutation_v] = new_add_code
        
                        else:
                            for i, k in zip(np.arange(0, np.abs(random_2 - random_1) + 1), np.arange(random_2, random_1 + 1)):
                                tem_list[i] = new_add_code[k]
        
                            tem_list = tem_list.tolist()
        
                            tem_list.reverse()
        
                            for i, k in zip(np.arange(0, np.abs(random_2 - random_1) + 1).tolist(),
                                            np.arange(random_2, random_1 + 1).tolist()):
                                new_add_code[k] = tem_list[i]
                            again_New_chrom1[mutation_v] = new_add_code
        
                    else:
                        again_New_chrom1[mutation_v] = new_add_code
                        
            chrom1 = again_New_chrom1
            chrom2 = begin_New_chrom2
            print("第%d代种群中最小的cost" % t, min_cost)
            print("最优运输方案\n", min_X)
            print('对应的位置', min_i)
            
            strmin_cost =str(min_cost)
            strmin_X = str(min_X)
            strmin_i = str(min_i)
            
            tResultText = f'第{t}代种群中最小的cost:'+strmin_cost+'\n'+"最优运输方案\n"+strmin_X+'\n'+'对应的位置'+strmin_i
            ResultText += tResultText

            if all_min_cost > min_cost:
                all_min_cost = min_cost
                all_min_X = min_X
                best_y = better_y
                min_t = t
            Result[t][0] = all_min_cost
            
        self.ui.textEdit.setPlainText(ResultText)
        
        
        
        with open('运行结果.txt','a+') as f: # 输出最优运输方案
            f.seek(0)
            f.truncate()
            f.write(ResultText)
            f.close()
        str1 =  str(all_min_cost)
        str2 = str(all_min_X)
        str3 = str(best_y)
        bestResult = "所有代中种群中最小的cost:" + str1 + '\n' + "所有代中的最优运输方案\n"+str2 + '\n' + "最优的选址方案\n" + str3 + '\n' +f"最优的选址方案出现在第{min_t}代"
        QMessageBox.about(self, '成功', '运行完成')
        with open('最优方案.txt','a+') as f: # 输出最优运输方案
            f.seek(0)
            f.truncate()
            f.write(bestResult)
            f.close()
        # print(Result)
            
        listbest = []
        for i in range(len(min_X)):
            listcol = []
            for j in range(len(min_X[0])):
                    listcol.append(min_X[i][j])
            listbest.append(listcol)
        # print(listall)
        path = os.getcwd() + '\\5.csv'
        # print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = listbest)
        test.to_csv(path,index=0)

        listcost = []
        for i in range(0,T):
            listcost.append(Result[i][0])
        # print(listcost)
        path = os.getcwd() + '\\6.csv'
        # print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = listcost)
        test.to_csv(path,index=0)
        
        listcost = []
        for i in range(len(best_y)):
            listcost.append(best_y[i])
        # print(listcost)
        path = os.getcwd() + '\\7.csv'
        # print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = listcost)
        test.to_csv(path,index=0)
            
    def printresult(self):
        
        with open("最优方案.txt", "r") as f:  # 打开文件
            data = f.read()
        self.ui.textEdit.setText(data)
    
    def clearall(self):
        self.ui.textEdit.clear()
        
    def outputPlanA(self):
        self.ui.tableWidget.clear()
        self.ui.tableWidget.setColumnCount(0)
        self.ui.tableWidget.setRowCount(0)    
        data = pd.read_csv('5.csv')
        Data = data.iloc[:,:].values.tolist() # 转换为list
        a = np.shape(data)[0] # 行数
        b = np.shape(data)[1] # 列数
        A = []
        B = []
        for i in range(1,a+1):
            A.append(f'物流中心{i}')
        for i in range(1,b+1):
            B.append(f'客户{i}')        
        tableWidget = self.ui.tableWidget
        tableWidget.setRowCount(a)
        tableWidget.setColumnCount(b)
        tableWidget.setHorizontalHeaderLabels(B)
        tableWidget.setVerticalHeaderLabels(A)

        for i in range(a):
            for j in range(b):
                newItem = QTableWidgetItem(str(Data[i][j]))
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget.setItem(i,j,newItem)
        tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)

    def outputPlanB(self):
        self.ui.tableWidget.clear()
        self.ui.tableWidget.setColumnCount(0)
        self.ui.tableWidget.setRowCount(0)    
        data = pd.read_csv('7.csv')
        Data = data.iloc[:,:].values.tolist() # 转换为list
        a = np.shape(data)[0] # 行数
        A = []
        for i in range(1,a+1):
            A.append(f'物流中心{i}')    
        tableWidget = self.ui.tableWidget
        tableWidget.setRowCount(1)
        tableWidget.setColumnCount(a)
        tableWidget.setHorizontalHeaderLabels(A)

        for i in range(a):
            if Data[i][0] ==1:
                newItem = QTableWidgetItem('选择')
            else:
                newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget.setItem(0,i,newItem)
        tableWidget.setEditTriggers(QAbstractItemView.NoEditTriggers)
        

    def clearResultO(self):
        self.ui.tableWidget.clear()
        self.ui.tableWidget.setColumnCount(0)
        self.ui.tableWidget.setRowCount(0)     
    
    def drawGraph(self):
        data = pd.read_csv('6.csv')
        Data = data.iloc[:,:].values.tolist() # 转换为list
        a = np.shape(data)[0] # 行数
        x = []
        y = []
        for i in range(a):
            x.append(i)
            y.append(Data[i][0])
        plt.plot(x,y,color='blue',linestyle='-',linewidth=1,label='Line1')
        plt.title('Iteration Graph')
        plt.xlabel('gen')
        plt.ylabel('value')
        plt.savefig('test.jpg',dpi=300) 
        
        pic = QPixmap('test.jpg')
        self.ui.label_pic.setPixmap(pic)
        self.ui.label_pic.setScaledContents(True)
    
    def clearGraph(self):
        self.ui.label_pic.clear()

if __name__=="__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())